define(["../com"], function() {
	
	var $info = $("#info");
	var $list = $("#car-list");
	$list.parseHtml().empty();
	$info.parseHtml().empty();	
	
	loadInfo();
	
	$(document).on('click', "[id^=carId_]", function() {
		$(this).id(1)
		$.post(g_domain + "/car/setDefault", {carId: $(this).id(1)}, function(data) {
			if (data.status !== 0) {
				data.code == "0" ? void(0) : alert(data.message);
				return;
			}
			alert("默认车辆设置成功！");
			location.href = "car-list.html?r=" + Math.random();
		})
	});
	
	$(document).on('click', "[id^=unbind_]", function() {
		if (!confirm("确定要解除绑定？")) {
			return;
		}
		$.post(g_domain + "/user/unbind", {carId: $(this).id(1)}, function(data) {
			if (data.status !== 0) {
				data.code == "0" ? void(0) : alert(data.message);
				return;
			}
			alert("解绑成功！");
			location.href = "car-list.html?r=" + Math.random();
		})
		return false;
	});
	
	function loadInfo() {
		$.post(g_domain + "/user?r=" + Math.random(), function(data) {
			if (data.status !== 0) {
				data.code == "0" ? void(0) : alert(data.message);
				return;
			}

			var user = data.result;
			var cars = user.cars;
			
			user.cars = [];
			$info.empty().parseHtml({data: user});
			
			for (var i in cars) {
				loadDetail(cars[i]);
			}
			
			$("#add-bt").click(function() {
				location.href = "car-add.html?mobile=" + user.mobile;
			});
			
		});
	}
	
	function loadDetail(car) {
		$.post(g_domain + "/user/qryvip?r=" + Math.random(), {carNo: car.carNo},function(data) {
			if (data.status !== 0) {
				data.code == "0" ? void(0) : alert(data.message);
				return;
			}
			
			var apiRes = $.parseJSON(data.result).response;
			$list.parseHtml({
				data: apiRes,
				beforeNode: {
					root: function(item) {
						item.carId = car.carId;
						var date = new Date();
						date.setTime(item.LastConsumDate);
						item.LastConsumDate = date.format("yyyy年MM月dd日");
						item.TotalAmount = item.TotalAmount || "0";
					}
				}
			});
		});
	}
});